﻿using System;
using System.Collections.Generic;
using System.Reflection;
using UnityEditor;
using UnityEngine;

namespace IQIGame.Onigao.GamePlay.Editors
{
    [CustomPropertyDrawer(typeof(SkillEditorNodeAttribute))]
    public class SkillEditorNodeDrawer: PropertyDrawer
    {
        private SkillEditorNodeAttribute customAttr;
        private List<string> valueStr = new List<string>();
        public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
        {
            if (this.customAttr == null)
            {
                this.customAttr = (SkillEditorNodeAttribute)this.fieldInfo.GetCustomAttribute(typeof(SkillEditorNodeAttribute), false);
            }
            if (this.valueStr.Count <= 0)
            {
                var rConfig = SkillEditorCustomSettingGlobal.GetConfig(this.customAttr.configKey);
                if (rConfig != null)
                {
                    this.valueStr.AddRange(rConfig.str);
                }
            }
            if (this.valueStr.Count > 0)
            {
                EditorGUILayout.BeginHorizontal(GUILayout.Height(20));
                EditorGUILayout.LabelField(this.customAttr.displayName);
                Rect popupRect = EditorGUI.IndentedRect(position);
                popupRect.x += popupRect.width;
                popupRect.y += popupRect.height;
                popupRect.width = 200;
                
                var rSelectValue = property.stringValue;
                var rDropdownBtn = EditorGUILayout.DropdownButton(new GUIContent(rSelectValue), FocusType.Passive);
                if (rDropdownBtn)
                {
                    SearchPopupWindow.Create(popupRect, this.valueStr, rSelectValue, (x) =>
                    {
                        property.stringValue = x;
                        property.serializedObject.ApplyModifiedProperties();
                    });
                }
                EditorGUILayout.EndHorizontal();
            }
        }
    }

    public class SkillEditorNodeAttribute : PropertyAttribute
    {
        public string displayName;
        public string configKey;

        public SkillEditorNodeAttribute(string displayName, string configKey)
        {
            this.displayName = displayName;
            this.configKey = configKey;
        }
    }
}